


package jnpf.zcasset.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.xuyanwu.spring.file.storage.FileInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.DownloadVO;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.config.ConfigValueUtil;
import jnpf.exception.DataException;
import jnpf.permission.entity.UserEntity;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcAssetEvaluateEntity;
import jnpf.zcasset.model.zcassetevaluate.ZcAssetEvaluateForm;
import jnpf.zcasset.model.zcassetevaluate.ZcAssetEvaluateInfoVO;
import jnpf.zcasset.model.zcassetevaluate.ZcAssetEvaluateListVO;
import jnpf.zcasset.model.zcassetevaluate.ZcAssetEvaluatePagination;
import jnpf.zcasset.service.ZcAssetEvaluateService;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 资产评估
 *
 * @版本： V3.2.0
 * @版权： 智果云科技（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期：
 */
@Slf4j
@RestController
@Api(tags = "资产评估", value = "zc")
@RequestMapping("/api/zc/ZcAssetEvaluate")
public class ZcAssetEvaluateController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private UserProvider userProvider;


    @Autowired
    private ZcAssetEvaluateService zcAssetEvaluateService;


    /**
     * 列表
     *
     * @param zcAssetEvaluatePagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZcAssetEvaluatePagination zcAssetEvaluatePagination) throws IOException {
        List<ZcAssetEvaluateEntity> list = zcAssetEvaluateService.getList(zcAssetEvaluatePagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcAssetEvaluateListVO> listVO = JsonUtil.getJsonToList(list, ZcAssetEvaluateListVO.class);
        for (ZcAssetEvaluateListVO zcAssetEvaluateVO : listVO) {
            zcAssetEvaluateVO.setAssetId_name(generaterSwapUtil.getDynName("612769091110831365", "ASSET_NAME", "id", "", zcAssetEvaluateVO.getAssetId(), false));
            zcAssetEvaluateVO.setAppraisalBaseDate_name(zcAssetEvaluateVO.getAppraisalBaseDate());
            zcAssetEvaluateVO.setAppraisalReportDate_name(zcAssetEvaluateVO.getAppraisalReportDate());
            zcAssetEvaluateVO.setEvaluationAgency_name(generaterSwapUtil.getDicName(zcAssetEvaluateVO.getEvaluationAgency(), "610824142995849541"));
            zcAssetEvaluateVO.setFairTotalPrice_name(zcAssetEvaluateVO.getFairTotalPrice());
            zcAssetEvaluateVO.setFairUnitPrice_name(zcAssetEvaluateVO.getFairUnitPrice());
            zcAssetEvaluateVO.setFairMarketRent_name(zcAssetEvaluateVO.getFairMarketRent());
            zcAssetEvaluateVO.setRemark_name(zcAssetEvaluateVO.getRemark());
            zcAssetEvaluateVO.setAttachmentUrls_name(generaterSwapUtil.getFileNameInJson(zcAssetEvaluateVO.getAttachmentUrls()));

            //子表数据转换
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zcAssetEvaluatePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param zcAssetEvaluateForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid ZcAssetEvaluateForm zcAssetEvaluateForm) throws DataException {
        boolean b = zcAssetEvaluateService.checkForm(zcAssetEvaluateForm, 0);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcAssetEvaluateEntity entity = JsonUtil.getJsonToBean(zcAssetEvaluateForm, ZcAssetEvaluateEntity.class);
        entity.setId(mainId);
        zcAssetEvaluateService.save(entity);


        return ActionResult.success("创建成功");
    }


    /**
     * 模板下载
     *
     * @return
     */
    @ApiOperation("模板下载")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = DownloadVO.builder().build();
        try {
            vo.setName("职员信息.xlsx");
            vo.setUrl(UploaderUtil.uploaderFile("/api/Common/DownloadModel?encryption=", userInfo.getId() + "#" + "职员信息.xlsx" + "#" + "Temporary"));
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
        }
        return ActionResult.success(vo);
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @ApiOperation("导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody ZcAssetEvaluatePagination zcAssetEvaluatePagination) throws IOException {
        if (StringUtil.isEmpty(zcAssetEvaluatePagination.getSelectKey())) {
            return ActionResult.fail("请选择导出字段");
        }
        List<ZcAssetEvaluateEntity> list = zcAssetEvaluateService.getTypeList(zcAssetEvaluatePagination, zcAssetEvaluatePagination.getDataType());
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcAssetEvaluateListVO> listVO = JsonUtil.getJsonToList(list, ZcAssetEvaluateListVO.class);
        for (ZcAssetEvaluateListVO zcAssetEvaluateVO : listVO) {
            zcAssetEvaluateVO.setAssetId_name(generaterSwapUtil.getDynName("612769091110831365", "ASSET_NAME", "id", "", zcAssetEvaluateVO.getAssetId(), false));

            zcAssetEvaluateVO.setAppraisalBaseDate_name(zcAssetEvaluateVO.getAppraisalBaseDate());

            zcAssetEvaluateVO.setAppraisalReportDate_name(zcAssetEvaluateVO.getAppraisalReportDate());

            zcAssetEvaluateVO.setEvaluationAgency_name(generaterSwapUtil.getDicName(zcAssetEvaluateVO.getEvaluationAgency(), "610824142995849541"));

            zcAssetEvaluateVO.setFairTotalPrice_name(zcAssetEvaluateVO.getFairTotalPrice());

            zcAssetEvaluateVO.setFairUnitPrice_name(zcAssetEvaluateVO.getFairUnitPrice());

            zcAssetEvaluateVO.setFairMarketRent_name(zcAssetEvaluateVO.getFairMarketRent());

            zcAssetEvaluateVO.setRemark_name(zcAssetEvaluateVO.getRemark());

            zcAssetEvaluateVO.setAttachmentUrls_name(generaterSwapUtil.getFileNameInJson(zcAssetEvaluateVO.getAttachmentUrls()));

            //子表数据转换
        }

        //转换为map输出
        List<Map<String, Object>> mapList = JsonUtil.getJsonToListMap(JsonUtil.getObjectToStringDateFormat(listVO, "yyyy-MM-dd HH:mm:ss"));
        mapList.stream().forEach(map -> {
            Map<String, Object> map2 = new HashMap<>();
            map.putAll(map2);
        });
        String[] keys = !StringUtil.isEmpty(zcAssetEvaluatePagination.getSelectKey()) ? zcAssetEvaluatePagination.getSelectKey().split(",") : new String[0];
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = this.creatModelExcel(configValueUtil.getTemporaryFilePath(), mapList, keys, userInfo);
        return ActionResult.success(vo);
    }

    //导出表格
    public DownloadVO creatModelExcel(String path, List<Map<String, Object>> list, String[] keys, UserInfo userInfo) {
        DownloadVO vo = DownloadVO.builder().build();
        List<ExcelExportEntity> entitys = new ArrayList<>();
        if (keys.length > 0) {
            for (String key : keys) {
                switch (key) {
                    case "assetId":
                        entitys.add(new ExcelExportEntity("资产信息", "assetId_name"));
                        break;
                    case "appraisalBaseDate":
                        entitys.add(new ExcelExportEntity("评估基准日", "appraisalBaseDate_name"));
                        break;
                    case "appraisalReportDate":
                        entitys.add(new ExcelExportEntity("评估报告日", "appraisalReportDate_name"));
                        break;
                    case "evaluationAgency":
                        entitys.add(new ExcelExportEntity("评估机构", "evaluationAgency_name"));
                        break;
                    case "fairTotalPrice":
                        entitys.add(new ExcelExportEntity("评估公允总价值", "fairTotalPrice_name"));
                        break;
                    case "fairUnitPrice":
                        entitys.add(new ExcelExportEntity("评估公允单价", "fairUnitPrice_name"));
                        break;
                    case "fairMarketRent":
                        entitys.add(new ExcelExportEntity("评估公允市场租金", "fairMarketRent_name"));
                        break;
                    case "remark":
                        entitys.add(new ExcelExportEntity("备注", "remark_name"));
                        break;
                    case "attachmentUrls":
                        entitys.add(new ExcelExportEntity("附件", "attachmentUrls_name"));
                        break;
                    default:
                        break;

                }
            }
            List<String> keylist = new ArrayList<>();
            for (String key : keys) {
                keylist.add(key);
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";

            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcAssetEvaluateInfoVO> info(@PathVariable("id") String id) {
        ZcAssetEvaluateEntity entity = zcAssetEvaluateService.getInfo(id);
        ZcAssetEvaluateInfoVO vo = JsonUtil.getJsonToBean(entity, ZcAssetEvaluateInfoVO.class);

        //子表
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<ZcAssetEvaluateInfoVO> detailInfo(@PathVariable("id") String id) {
        ZcAssetEvaluateEntity entity = zcAssetEvaluateService.getInfo(id);
        ZcAssetEvaluateInfoVO vo = JsonUtil.getJsonToBean(entity, ZcAssetEvaluateInfoVO.class);
        //子表数据转换
        //附表数据转换
        //添加到详情表单对象中
        vo.setAssetId(generaterSwapUtil.getDynName("612769091110831365", "ASSET_NAME", "id", "", vo.getAssetId(), false));
        vo.setAppraisalBaseDate(vo.getAppraisalBaseDate());
        vo.setAppraisalReportDate(vo.getAppraisalReportDate());
        vo.setEvaluationAgency(generaterSwapUtil.getDicName(vo.getEvaluationAgency(), "610824142995849541"));
        vo.setFairTotalPrice(vo.getFairTotalPrice());
        vo.setFairUnitPrice(vo.getFairUnitPrice());
        vo.setFairMarketRent(vo.getFairMarketRent());
        vo.setRemark(vo.getRemark());
        vo.setAttachmentUrls(generaterSwapUtil.getFileNameInJson(vo.getAttachmentUrls()));
        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param zcAssetEvaluateForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZcAssetEvaluateForm zcAssetEvaluateForm) throws DataException {
        boolean b = zcAssetEvaluateService.checkForm(zcAssetEvaluateForm, 1);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        UserInfo userInfo = userProvider.get();
        ZcAssetEvaluateEntity entity = zcAssetEvaluateService.getInfo(id);
        if (entity != null) {
            ZcAssetEvaluateEntity subentity = JsonUtil.getJsonToBean(zcAssetEvaluateForm, ZcAssetEvaluateEntity.class);
            boolean b1 = zcAssetEvaluateService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZcAssetEvaluateEntity entity = zcAssetEvaluateService.getInfo(id);
        if (entity != null) {
            zcAssetEvaluateService.delete(entity);

        }
        return ActionResult.success("删除成功");
    }


}
